package xyz.zcq.springframework.beans.factory.support;

import xyz.zcq.springframework.beans.BeanException;
import xyz.zcq.springframework.beans.factory.config.BeanDefinition;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 简单的实例化策略
 */
public class SimpleInstantiationStrategy implements InstantiationStrategy {

    @Override
    public Object instantiate(BeanDefinition definition, String beanName,
                              Constructor<?> constructor, Object[] args) {
        Class<?> clazz = definition.getBeanClass();
        try {
            if (constructor != null) {
                return clazz.getDeclaredConstructor(constructor.getParameterTypes()).newInstance(args);
            } else {
                return clazz.newInstance();
            }
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException |
                 NoSuchMethodException e) {
            throw new BeanException("Failed to instantiate bean [" + clazz.getName() + "]", e);
        }
    }

}
